package com.lap.web.starter.shared;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;

/**
 * URI 工具类
 *
 * @author Shuisheng.Lao
 * @version 0.0.1
 */
@UtilityClass
public class UriUtil {

  private static final String SLASH = "/";
  private static final String REGEX = "\\{\\w+\\}";
  private static final String UNDER_LINE = "_";
  private static final String LINE = "-";
  private static final String PERIODS = ".";

  /**
   * 获取URI
   *
   * <ul>
   *   <li>parentUri: "", [] =>""
   *   <li>parentUri: "api",["test","a"] => /api/test
   * </ul>
   *
   * @param parentUri 父uri
   * @param uriParts uri数组
   * @return 集合
   */
  public static String getUri(String parentUri, String... uriParts) {
    // 处理空输入
    if ((parentUri == null || parentUri.trim().isEmpty())
        && (uriParts == null || uriParts.length == 0)) {
      return "";
    }

    // 构建路径
    StringBuilder pathBuilder = new StringBuilder();

    // 添加父URI
    if (parentUri != null && !parentUri.trim().isEmpty()) {
      pathBuilder.append(parentUri.trim());
    }

    // 添加URI部分 - 只取第一个非空元素
    if (uriParts != null) {
      for (String part : uriParts) {
        if (part != null && !part.trim().isEmpty()) {
          // 只取第一个非空元素，添加后立即跳出循环
          if (!pathBuilder.isEmpty() && !pathBuilder.toString().endsWith("/")) {
            pathBuilder.append("/");
          }
          pathBuilder.append(part.trim());
          break; // 只取第一个，立即跳出循环
        }
      }
    }

    // 规范化并返回
    return normalizePath(pathBuilder.toString());
  }

  private static String normalizePath(String path) {
    if (path == null || path.trim().isEmpty()) {
      return "";
    }

    String normalized = path.trim();

    // 处理特殊情况：只有斜杠
    if (normalized.equals("/")) {
      return "/";
    }

    // 步骤1：将所有连续斜杠替换为单个斜杠
    normalized = normalized.replaceAll("/+", "/");

    // 步骤2：确保以斜杠开头
    if (!normalized.startsWith("/")) {
      normalized = "/" + normalized;
    }

    // 步骤3：移除末尾斜杠（除非是根路径）
    if (normalized.length() > 1 && normalized.endsWith("/")) {
      normalized = normalized.substring(0, normalized.length() - 1);
    }

    return normalized;
  }

  /**
   * 根据模块和uri获取编码
   *
   * @param clazz 类型
   * @return 返回uri
   */
  public static String getClassName(Class<?> clazz) {
    StringBuilder result = new StringBuilder(32);

    String packageName = clazz.getPackageName();
    if (StringUtils.isNotBlank(packageName)) {
      result.append(packageName).append(PERIODS);
    }

    String name = clazz.getSimpleName();
    if (StringUtils.isNotBlank(name)) {
      result.append(name);
    }
    return result.toString();
  }

  /**
   * 获取uri_code
   *
   * <ul>
   *   <li>module: test
   *   <li>method: get
   *   <li>uri: /api/user
   *   <li>结果: test_get_api_user
   * </ul>
   *
   * @param module 模块
   * @param uri URI
   * @param method 方法
   * @return URI编码
   */
  public static String getUriCode(String module, String uri, String method) {
    StringBuilder sb = new StringBuilder(256);

    if (StringUtils.isNotBlank(module)) {
      sb.append(module);
    }

    if (StringUtils.isNotBlank(method)) {
      appendWithUnderscore(sb, method.toLowerCase());
    }

    if (StringUtils.isNotBlank(uri)) {
      Pattern pattern = Pattern.compile(REGEX);
      Matcher matcher = pattern.matcher(uri);

      // 先替换路径参数，然后处理斜杠
      String newUri = matcher.replaceAll("id");

      // 去除开头和结尾的斜杠，避免产生连续的下划线
      newUri = newUri.replaceAll("^/|/$", "");

      // 替换剩余的斜杠和连字符为下划线
      newUri = newUri.replace(SLASH, UNDER_LINE).replace(LINE, UNDER_LINE);

      appendWithUnderscore(sb, newUri);
    }

    return sb.toString();
  }

  private static void appendWithUnderscore(StringBuilder sb, String value) {
    if (StringUtils.isNotBlank(value)) {
      if (!sb.isEmpty()) {
        sb.append(UNDER_LINE);
      }
      sb.append(value);
    }
  }
}
